import i18n from '@/i18n'
import { AppConfig } from '@apps/server/config/entity/app-config.entity'
import { Assist, FileUtil, md5 } from '@libs/lhy-common'
import { CoreConfigService, ParseImageFilePipe } from '@libs/lhy-core'
import { HttpService } from '@nestjs/axios'
import { Body, Controller, Post, UploadedFile, UseInterceptors } from '@nestjs/common'
import { FileInterceptor } from '@nestjs/platform-express'
import { ApiBody, ApiConsumes, ApiOperation, ApiProduces, ApiTags } from '@nestjs/swagger'
import { FlowCommonDownloadImageFromRemoteDto } from './dto/flow-common-download-image-from-remote.dto'
import { FlowCommonUploadImageDto } from './dto/flow-common-upload-image.dto'

@ApiTags(i18n.t('app-flow.flow-common.flow-common.12153257-0'))
@Controller({
  path: 'common',
  version: '1',
})
export class FlowCommonController {
  constructor(
    private readonly configService: CoreConfigService<AppConfig>,
    private httpService: HttpService
  ) {}

  @ApiOperation({ summary: i18n.t('app-flow.flow-common.flow-common.12153257-1') })
  @ApiConsumes('multipart/form-data')
  @ApiProduces('application/text')
  @ApiBody({ type: FlowCommonUploadImageDto })
  @Post('upload_image')
  @UseInterceptors(FileInterceptor('file'))
  async uploadImage(
    @UploadedFile(ParseImageFilePipe)
    file: Express.Multer.File
  ): Promise<string> {
    const fileMd5 = FileUtil.getFileMd5(file)
    const fileExt = FileUtil.getFileExt(file)
    const fileName = fileExt ? `${fileMd5}.${fileExt}` : fileMd5

    const { storePath, storeUrl } = this.configService.config.getFlowUploadImageStorePath(fileName)
    await FileUtil.saveFile(storePath, file)

    return storeUrl
  }

  @ApiOperation({ summary: i18n.t('app-flow.flow-common.flow-common.12153257-2') })
  @Post('download_image_from_remote')
  async downloadImageFromRemote(@Body() param: FlowCommonDownloadImageFromRemoteDto): Promise<string> {
    try {
      const res = await this.httpService.axiosRef.get<ArrayBuffer>(param.url, { responseType: 'arraybuffer' })
      const imageData = Buffer.from(Assist.notNull(res.data, i18n.t('app-flow.flow-common.flow-common.12153257-3')))

      const fileMd5 = md5(imageData)
      const fileExt = FileUtil.getUrlExt(param.url)
      const fileName = fileExt ? `${fileMd5}.${fileExt}` : fileMd5

      const { storePath, storeUrl } = this.configService.config.getFlowUploadImageStorePath(fileName)
      await FileUtil.saveBinaryFile(storePath, imageData)

      return storeUrl
    } catch (e) {
      Assist.threw(e)
    }
  }
}
